package daoJPA;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;

import dao.ICandidateDAO;
import entityJPA.Candidate;

public class JPACandidateDAO implements ICandidateDAO, Serializable {

	private EntityManagerFactory emf=null;
	public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }
	public JPACandidateDAO(EntityManagerFactory e) {
		emf=e;
	}
	
	
	@Override
	public void insertCandidate(Candidate canditate) {
		// TODO Auto-generated method stub
		EntityManager em=getEntityManager();
		try{
			em.getTransaction().begin();
			em.persist(canditate);
			em.getTransaction().commit();
		}
		catch (Exception ex){
			ex.printStackTrace();
		}
		em.close();
		
	}

	@Override
	public void updateCandidate(Candidate candidate) {
		// TODO Auto-generated method stub
		EntityManager em=getEntityManager();
		try{
			em.getTransaction().begin();
			em.merge(candidate);
			em.getTransaction().commit();
		}
		catch (Exception ex){
			ex.printStackTrace();
		}
		em.close();
	}

	@Override
	public void deleteCandidate(Candidate candidate) {
		EntityManager em =getEntityManager();
		try{
			em = getEntityManager();
			em.getTransaction().begin();
			Candidate c = em.getReference(Candidate.class, candidate.getIdCandidate());
	          c.getIdCandidate();		
			em.remove(c);
		
		//	em.remove(em.merge(candidate));
			em.getTransaction().commit();
		}catch (Exception ex){
			ex.printStackTrace();
		}
		finally{
			 if (em != null) {
	                em.close();
	            }
		}
		
	}

	@Override
	public Candidate findById(int idCandidate) {
		EntityManager em = getEntityManager();
		Candidate c=null;
		try{
			c=em.find(Candidate.class, idCandidate);
		}catch (Exception ex){
			ex.printStackTrace();
		}
		finally{
			em.close();
		}
		return c;
	}

	@Override
	public List<Candidate> findAll() {
		EntityManager em =getEntityManager();
		CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Candidate.class));
        Query q = em.createQuery(cq);
        return q.getResultList();
		

	}

}
